import 'package:flutter/cupertino.dart';
import 'package:infinite_scroll_pagination/infinite_scroll_pagination.dart';

import '../../../data/models/bt_friend.dart';
import '../../utils/bt_constants.dart';
import '../../utils/bt_event_bus.dart';
import '../repository/bt_followed_repository.dart';
import '../repository/bt_message_repository.dart';

class BtFollowedListModel extends ChangeNotifier {
  final int _pageSize = 20;

  final PagingController<int, BtFriend> _pagingController = PagingController(firstPageKey: 0);

  PagingController<int, BtFriend> get pagingController => _pagingController;

  late PageRequestListener<int> _listener;

  late final BtFollowedRepository repository;

  late final BtMessageRepository messageRepository;

  BtFollowedListModel() {
    repository = BtFollowedRepository();
    messageRepository = BtMessageRepository();

    _listener = (pageKey) {
      pageKey++;
      fetchFriendList(pageKey);
    };
    _pagingController.addPageRequestListener(_listener);

    eventBus.on<BtEventFn>().listen((event) {
      if (event.refresh == freshFollowedList) {
        _pagingController.refresh();
      }
    });
  }

  void fetchFriendList(int pageKey) {
    repository.getFriendList(pageKey, _pageSize, (btFriendList) {
      try {
        final newItems = btFriendList;
        final isLastPage = newItems.length < _pageSize;
        if (isLastPage) {
          _pagingController.appendLastPage(newItems);
        } else {
          _pagingController.appendPage(newItems, pageKey);
        }
      } catch (error) {
        _pagingController.error = error;
      }
    }, (error) => _pagingController.error = error);
  }

  void unfriend(String followUserId, Function(bool success, String msg) onResult) {
    messageRepository.unfriend(followUserId, onResult);
  }
}
